
/**
 * 创建ISSOnline设备:目前支持 所有身份证阅读器 \聚盾证件扫描仪 FS531-U \条码扫描枪 N4313 民德ES4200 激光 串口COM1
 * @param setting json格式：{设备类型：不需要则不传
 * 							Cert\Barcode\Scanner : {回调函数 'callBack' 参数为设备返回值，参见ISSO接口，
 * 													访问设备jquery 选择器 'select'，click事件触发访问设备指令
 * 													}，
 * 							Methods 自定义方法，不传则执行默认方法
 * 							showMessage ：接收执行结果，参数：type：sucess\warning\error message:返回的错误信息
 * 							checkWebServer ：检测驱动是否安装  return type : boolean
 * 							downloadDrive : 下载驱动
 */
var ISSOnlineUrl = "http://127.0.0.1:24008/ISSOnline";
var canConnectDriver = false;
/**
 *
 * @returns {string}
 */

function createISSonlineDevice(setting)
{
	//刷卡信息返回默认方法
	if(typeof setting.Methods == "object")
	{
		//检查驱动安装默认方法
		if(typeof setting.Methods.checkWebServer != "function")
		{
			setting.Methods.checkWebServer = function(myDevice)
			{
				var ISSVersion = function(){};
				ZK.extend(ISSVersion, BaseDevice, {
					message : "",
					url : "/info",
                    async: true,
					interfaceResult : CertReault,
					dealDeviceData:function(result){
                        setting.Methods.showScan();
						if(result.data.server_version >= "2.0.8")
						{
							if(typeof myDevice == "object")
							{
								//连接设备，处理返回信息
								setTimeout(function(){
									myDevice.accessDevice();
								},100);
							}
						}
						else
						{
							if(typeof myDevice == "object")
							{
								//连接设备，处理返回信息
								setTimeout(function(){
									myDevice.accessDevice();
								},100);
							}
							else
							{
								if(typeof setting.Methods.notInstall == "function")
								{
									setting.Methods.notInstall();
								}
							}
						}
					},
					installDrive:function(){
						if(typeof myDevice == "object")
						{
							closeMessage();
							//驱动未安装
							setting.Methods.downloadDrive();
						}
						else
						{
							if(typeof setting.Methods.notInstall == "function")
							{
								setting.Methods.notInstall();
							}
						}
					}
				});
				var version = new ISSVersion();
				version.accessDevice();
			}
		}
		//下载驱动默认方法
		if(typeof setting.Methods.downloadDrive != "function")
		{
			setting.Methods.downloadDrive = function()
			{
                //驱动下载实现部分
			}
		}
	}
	/**
	 * 设备
	 */
	var BaseDevice = function()
	{
		message : ""
	};
	//设备工厂
	BaseDevice.prototype.createDevice = function(setting)
	{
	    var Driver = function(){};
        var driver =  this.initDevice(Driver, setting);
        return driver;
    };
    //初始化设备
    BaseDevice.prototype.initDevice = function(Driver, setting){

        ZK.extend(Driver, BaseDevice,{
            url: setting.url,
            async: setting.async,
            interfaceResult: setting.interfaceResult,
            dealDeviceData: setting.callBack
        })
        return new Driver();
    }
	//信息显示
	BaseDevice.prototype.setMessage = function()
	{

		setting.Methods.showMessage(this.message);
	};

	//处理硬件返回值
	BaseDevice.prototype.dealDeviceInfo = function(result) {
        if (result === null || result.ret === null) {
            return;
        }
        //信息提示
        var info = this.interfaceResult[result.ret];
        if (info == undefined) {
            return;
        }
        if (info.notShow == undefined) {

        }
        //处理数据
        if ("success" === info.type) {
            this.dealDeviceData(result);
        }else{
            this.message = info;
            this.setMessage();
        }
    }
	//html5使用ajax方式访问服务
	BaseDevice.prototype.ajaxAccess = function(url, async)
	{
		var result = null;
		var parent = this;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", ISSOnlineUrl+url, async);
        xhr.send();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4){ //请求结束
                if(xhr.status == 200) { //请求成功
                    var resultData = xhr.responseText;
                    resultData = resultData.replace(/\\/g, "/");
                    result = JSON.parse(resultData);
                    parent.dealDeviceInfo(result);
                }
            }
        }
	}
	
	//IE8、IE9访问服务
	BaseDevice.prototype.xDomainAccess = function(url, async)
	{
		var parent = this;
		var xDomainRequest = new XDomainRequest();
		if (xDomainRequest) 
		{ 
			xDomainRequest.timeout=10000;
			xDomainRequest.open('GET', ISSOnlineUrl+url, async);
			xDomainRequest.onload = function()
			{
				var resultData = xDomainRequest.responseText;
				resultData = resultData.replace(/\\/g,"/");
                var obj = JSON.parse(resultData);
                parent.dealDeviceInfo(obj);
			};
			xDomainRequest.onerror = function()
			{
				//用完后，将对象置为空
				xDomainRequest = null;
			};
			xDomainRequest.ontimeout = function()
			{
				//用完后，将对象置为空
				xDomainRequest = null;
			};
			xDomainRequest.send();
		}
	}
	
	//驱动检测
	BaseDevice.prototype.installDrive = function()
	{
		
	}
    var browserFlag = getBrowserType() || "";
	//设备通信,得到硬件返回的数据
	BaseDevice.prototype.accessDevice = function()
	{
		if(browserFlag == "html5")
		{
			this.ajaxAccess(this.url, this.async);
		}
		else if(browserFlag == "simple")
		{
			this.xDomainAccess(this.url, this.async);
		}
		else
		{
			if(window.console)
			{
				console.error("browserFlag is missing");
			}
		}
	};
	for(var driver in setting){
        if(driver != 'Methods') {
            var myDeviceSetting = setting[driver];
            var elem = myDeviceSetting.select;
            $(elem).unbind().click(function (e) {
                if(canConnectDriver) {
                    $(elem).blur();
                    var baseDevice = new BaseDevice();
                    var myDevice = baseDevice.createDevice(myDeviceSetting);
                    setting.Methods.checkWebServer(myDevice);
                }else{
                    alertDialog();
                }
            });
        }
    }
	setting.Methods.checkWebServer();
};
var CertReault = {
    0:{mean:gettext("成功"),message:gettext("二代身份证读取成功！"),type:"success"},
    1:{mean:gettext("端口打开失败"),message:gettext("未检测到二代身份证阅读器！"),type:"warning"},
    2:{mean:gettext("数据传输超时"),message:gettext("未检测到二代身份证阅读器！"),type:"error"},
    10:{mean:gettext("没有找到卡"),message:gettext("未读取到身份证，请重新刷卡！"),type:"warning"},
    11:{mean:gettext("读卡操作失败"),message:gettext("未检测到身份证阅读器！"),type:"error"},
    20:{mean:gettext("自检失败"),message:gettext("二代身份证读取失败！"),type:"error"},
    30:{mean:gettext("其他错误"),message:gettext("二代身份证读取失败！"),type:"error"},
    40:{mean:gettext("相片解码失败"),message:gettext("二代身份证读取失败！"),type:"error"},
    100:{mean:gettext("超时"),message:gettext("未读取到身份证，请重新刷卡！"),type:"warning"},
    200:{mean:"GetBase64PhotoData",message:gettext("二代身份证读取失败！"),type:"error"}
}
var setting = {
	Cert:{
		select:"#id_scan_card",
        url:"/ScanReadIdCardInfo?OP-DEV=1&CMD-URL=4&common=1" + "&random=" + getRandomNum(),
        async:true,
        interfaceResult : CertReault,
        callBack: function(result) {
			setFormData(result);
		}
	},
	Methods : {
        checkWebServer: true,
        showScan: function(){
            canConnectDriver = true;
            $("#id_scan_card").addClass('linkStyle');
            $("#id_scan_card").removeAttr('style');
            $("#id_scan_card").removeAttr('title');
            $('#scan_info').html('');
        },
        showMessage: function(msg){
            var error = '<span class="cert_error">'+msg.message+'</span>';
            $('#scan_info').html(error);
        }
	}
};
createISSonlineDevice(setting);